package com.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.exam.pojo.domain.Ranking;
import com.exam.pojo.vo.RankingVO;
import com.exam.service.IRankingService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class RankingServiceImpl implements IRankingService {
    
    private final MongoTemplate mongoTemplate;
    @Override
    public List<RankingVO> list() {
        //按照duration升序，取前100条
        Query query = new Query();
        List<Sort.Order> orders = new ArrayList<>();
        //先按照题目数量降序
        Sort.Order questionNumDesc = new Sort.Order(Sort.Direction.DESC,"nums");
        orders.add(questionNumDesc);
        //按照正确率降序
        Sort.Order questionRateDesc = new Sort.Order(Sort.Direction.DESC,"rate");
        orders.add(questionRateDesc);
        //按照时间升序
        Sort.Order questionDurationAsc = new Sort.Order(Sort.Direction.ASC,"duration");
        orders.add(questionDurationAsc);

        Sort sort = Sort.by(orders);
        query.with(sort);
        query.limit(100);
        List<Ranking> rankings = mongoTemplate.find(query, Ranking.class);
        //处理结果
        return BeanUtil.copyToList(rankings,RankingVO.class);
    }
    @Override
    public void add(Ranking dto) {
        //查询记录是否存在
        Ranking ranking = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getId())),Ranking.class);
        if(ranking == null){
            mongoTemplate.insert(dto);
        }else{
            //判断是否需要更新记录
            if(dto.getDuration() < ranking.getDuration()){
                mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(dto.getId())),
                Update.update("duration",dto.getDuration())
                .set("nickName",dto.getNickName())
                .set("headImg",dto.getHeadImg())
                .set("rate",dto.getRate()),
                Ranking.class);
            }
        }
    }
}
